
package cn.uestc.labhms.modules.sys.service.impl;

import cn.uestc.labhms.common.utils.Constant;
import cn.uestc.labhms.modules.hms.dao.HmsUserPermDao;
import cn.uestc.labhms.modules.hms.entity.HmsUserPermEntity;
import cn.uestc.labhms.modules.hms.service.UserPermService;
import cn.uestc.labhms.modules.sys.dao.SysMenuDao;
import cn.uestc.labhms.modules.sys.dao.SysUserDao;
import cn.uestc.labhms.modules.sys.dao.SysUserTokenDao;
import cn.uestc.labhms.modules.sys.entity.SysMenuEntity;
import cn.uestc.labhms.modules.sys.entity.SysUserEntity;
import cn.uestc.labhms.modules.sys.entity.SysUserTokenEntity;
import cn.uestc.labhms.modules.sys.service.ShiroService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ShiroServiceImpl implements ShiroService {
    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserTokenDao sysUserTokenDao;
    @Autowired
    private HmsUserPermDao userPermDao;

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if(userId == Constant.SUPER_ADMIN){
            List<SysMenuEntity> menuList = sysMenuDao.selectList(null);
            permsList = new ArrayList<>(menuList.size());
            for(SysMenuEntity menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
//            permsList = sysUserDao.queryAllPerms(userId);

            permsList = new LinkedList<>();
            List<HmsUserPermEntity> userPermEntities = userPermDao.selectList(new QueryWrapper<HmsUserPermEntity>()
                    .eq("user_id", userId));
            userPermEntities.forEach(userPermEntity -> {
                permsList.add(userPermEntity.getPermission());
            });
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public SysUserTokenEntity queryByToken(String token) {
        return sysUserTokenDao.queryByToken(token);
    }

    @Override
    public SysUserEntity queryUser(Long userId) {
        return sysUserDao.selectById(userId);
    }
}
